import { login, logout } from '@/api/login';
import { useRequest } from 'alova';
import { defineStore } from 'pinia';
import { arrayToTree } from '@/utils/util';
import { Names } from './store-name';
import type { RouteRecordRaw } from "vue-router";
import type { TActionInfo, TMenuInfo, TMenus } from '@/typing/base';

export const useUserStore = defineStore(Names.USER, {
  state: () => {
    return {
      username: '',
      userInfo: {},
      asideExpand: true,
      menuData: <TMenuInfo[]>[],
      actionList: <TActionInfo[]>[],
      asideRoutes: <RouteRecordRaw[]>[]
    }
  },
  persist: true,
  getters: {
    getRoutes(): TMenus[] {
      return arrayToTree(this.menuData)
    }
  },
  actions: {
     userLogin(req: ILoginReq, fn: Function) {
      const { onSuccess } = useRequest(
        login(req)
      );
      onSuccess(({ data }: any) => {
        const { username, token, menuData, actionListJson } = data.data as ILoginRes
        localStorage.setItem('token', token)
        console.log('*********', data)
        this.username = username
        this.menuData = menuData || []
        this.actionList = actionListJson
        fn && fn()
      })

    },
    loginout(fn: Function) {
      const { onSuccess } = useRequest(
        logout()
      );
      onSuccess(({ data }: any) => {
        if (data.data.logout) {
          localStorage.removeItem('token')
          fn && fn()
        }
      })

    }
  }
})
